package com.cp.mtq.test.stack;

import java.util.Stack;

/**
 * 计算堆栈当前元素的最大值
 */
public class MaxStack {
    private Stack<Integer> stack = new Stack<Integer>();
    private int maxVal = Integer.MIN_VALUE;
    private Stack<Integer> maxStack = new Stack<Integer>();

    public void push(int val) {
        if (val >= maxVal) {
            maxVal = val;
            maxStack.push(maxVal);
        }

        stack.push(val);
    }

    public int peek() {
        return stack.peek();
    }

    public int pop() {
        if (stack.peek() == maxVal) {
            maxStack.pop();
        }

        maxVal = maxStack.peek();

        return stack.pop();
    }

    public int max() {
        return maxStack.peek();
    }

    public static void main(String[] args) {
        MaxStack ms = new MaxStack();
        ms.push(5);
        ms.push(4);
        ms.push(2);
        ms.push(3);

        System.out.println("Max Val in stack is : " + ms.max());

        ms.push(6);
        ms.push(1);
        ms.push(10);
        ms.push(8);
        System.out.println("Max Val in stack is : " + ms.max());

        ms.pop();
        ms.pop();
        System.out.println("Max Val in stack is : " + ms.max());

        ms.push(7);
        System.out.println("Max Val in stack is : " + ms.max());

    }
}
